package com.project.base.baseproject.ModelManager.UserMananger;

import android.content.Context;

import com.project.base.baseproject.AppCustoms.MyApplication.MyApplication;
import com.project.base.baseproject.ModelManager.Models.EventBusClass;
import com.project.base.baseproject.ModelManager.Models.User;
import com.project.base.baseproject.Utikles.ThirdParty.RunInMainThread.UIKit;

import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.Date;
import io.realm.Realm;
import io.realm.RealmConfiguration;
import io.realm.RealmResults;

/**
 * Created by mac on 2016/11/29.
 */
//模型采用查询型设计，属性有其他属性数组则使用ID数组，用时再在另一张表中查找
//查询型设计一般存在web端，为了节省流量
//要获取数据库数据都重新得到实例：Realm realm = Realm.getDefaultInstance();
//改变了数据库，就用EventBus发一个通知，其他界面按需求监听通知
public class UserManager {
    private static UserManager instance = null;
    //用户信息
    public User user = null;
    public static UserManager manager(){
        if(null == instance)
            instance = new UserManager();
        return instance;
    }
    //######------用户操作 begin------######
    //通过user_guid加载用户 一个用户一个单独的数据库文件
    public void loadUserInfo() {
        RealmConfiguration configuration = new RealmConfiguration.Builder(MyApplication.getInstance()).name("baseproject")
                .deleteRealmIfMigrationNeeded().schemaVersion(1).build();
        Realm.setDefaultConfiguration(configuration);
        Realm realm = Realm.getDefaultInstance();
        RealmResults<User> userRealmResults = realm.where(User.class).findAll();
        if(userRealmResults.size() == 0)
            this.user = new User();
        else
            this.user = realm.copyFromRealm(userRealmResults.get(0));
        realm.close();
    }
    //清除所有信息
    public void clearData() {
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        realm.clear(User.class);
        realm.commitTransaction();
    }
    //更新当前用户
    public void updateUser(User user) {
        Realm realm = Realm.getDefaultInstance();
        realm.beginTransaction();
        RealmResults<User> userRealmResults = realm.where(User.class).findAll();
        while (userRealmResults.size() > 0)
            userRealmResults.get(0).removeFromRealm();
        realm.createOrUpdateObjectFromJson(User.class,User.jsonString(user));
        this.user = user;
        realm.commitTransaction();
        UIKit.runOnMainThreadAsync(new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().post(new EventBusClass(EventBusClass.UserInfoChangeEvent,""));
            }
        });
        realm.close();
    }
    //######------用户操作 end------######
}